import sys
import time
from api.mod import ComPort, ComPortCmd
from api.cp8212com485 import CP8212ComPort485Model
from logging import ERROR, INFO, WARNING

from log import CP8212_VOLTAGE_IDENT, add_log
DISPLAY_TXT_GLOBAL = {"txt": "", "list": [], "level": INFO, "label": ""}

def main(args):
    count = 3
    v_low = -100
    v_high = 10000
    model = CP8212ComPort485Model(port="",flag="CH340",timeout=1)
    cport = ComPort(model)
    DISPLAY_TXT_GLOBAL["label"] = "电池电压："
    for i in range(20):
        try: 
            cport.connect()
            count_list = []
            for _ in range(0,count):
                cport.model.set_cmd(ComPortCmd.Current)
                cport.send()
                rec = cport.receive()
                res = cport.parse(rec)
                if res != None:
                    DISPLAY_TXT_GLOBAL["txt"] = f"{res.value}{cport.model.unit}"
                    DISPLAY_TXT_GLOBAL["level"] = INFO
                    add_log(f"{res.value}{cport.model.unit}",INFO,CP8212_VOLTAGE_IDENT)
                    count_list.append(res.value)
                else:
                    DISPLAY_TXT_GLOBAL["txt"] = "0"
                    DISPLAY_TXT_GLOBAL["level"] = ERROR
                    add_log(f"无法正常获取数据,请确保模块正常运行",WARNING,CP8212_VOLTAGE_IDENT)
                    count_list.append(0)
            cport.disconnect()
            merge = sum(count_list) / len(count_list)
            s = f"计算平均值={merge}{cport.model.unit} 计算次数=[{len(count_list)} 规则={v_low} < {merge} < {v_high}]"
            if merge > v_low and merge < v_high:
                add_log(s,INFO,CP8212_VOLTAGE_IDENT)
                # return True
            else:
                add_log(s,WARNING,CP8212_VOLTAGE_IDENT)
        except:
            add_log(f"无法正常连接模块，正在尝试重新连接",WARNING,CP8212_VOLTAGE_IDENT)
        time.sleep(1)


if __name__ == "__main__":
    main(sys.argv)

